package com.jk.smartelderlycare.controller;

import com.jk.smartelderlycare.dao.ProductDao;
import com.jk.smartelderlycare.entity.Product;
import com.jk.smartelderlycare.pojo.PagedResponse;
import com.jk.smartelderlycare.pojo.ResponseResult;

import com.jk.smartelderlycare.utils.PaginationUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hhk
 * @version 1.0
 * @ClassName ProductController
 * @program: smart-elderly-care
 * @description: TODO
 * @date 2024/11/12 14:40
 */
@Api(tags = "商品索引模块")
@RestController
@RequestMapping(value = "product")
public class ProductController {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    /**
     * @description: 商品新增
     * @param: [product]
     * @return: com.jk.smartelderlycare.pojo.ResponseResult
     * @author hhk
     * @date: 2024/11/12 14:51
     */
    @ApiOperation(value = "商品新增",httpMethod = "POST",notes = "商品新增")
    @PostMapping(value = "/addProduct")
    public ResponseResult addProduct(@RequestBody Product product){
        try {
            productDao.save(product);
            return new ResponseResult(200,"新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500,"新增失败");
        }
    }

    /**
     * @description: 批量新增
     * @param: [productList]
     * @return: com.jk.smartelderlycare.pojo.ResponseResult
     * @author hhk
     * @date: 2024/11/12 14:56
     */
    @ApiOperation(value = "批量新增",httpMethod = "POST",notes = "批量新增")
    @PostMapping(value = "/testBatchAdd")
    public ResponseResult testBatchAdd(@RequestBody List<Product> productList){
        try {
            productDao.saveAll(productList);
            return new ResponseResult(200,"新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500,"新增失败");
        }

    }
    /**
     * @description: 通过id获取商品信息
     * @param: [id]
     * @return: com.jk.smartelderlycare.pojo.ResponseResult<com.jk.smartelderlycare.entity.Product>
     * @author hhk
     * @date: 2024/11/12 14:59
     */
    @ApiOperation(value = "通过id获取商品信息",httpMethod = "GET",notes = "通过id获取商品信息")
    @GetMapping(value = "/findProductById")
    public ResponseResult<Product> findProductById(Long id){
        return new ResponseResult<Product>(200,"查询成功",productDao.findById(id).get());
    }
    /** 
     * @description: 查询商品
     * @param: []
     * @return: com.jk.smartelderlycare.pojo.ResponseResult<java.util.List<com.jk.smartelderlycare.entity.Product>>
     * @author hhk
     * @date: 2024/11/12 16:07
     */ 
    @ApiOperation(value = "查询商品",httpMethod = "GET",notes = "查询商品")
    @GetMapping(value = "/findProduclist")
    public ResponseResult<List<Product>> findProductlist(){
        List<Product> list = new ArrayList<>();

//        Iterable<Product> iterable = productDao.findAll();
//        Iterator<Product> iterator = iterable.iterator();
//        while (iterator.hasNext()) {
//            list.add(iterator.next());
//        }
        productDao.findAll().forEach(item -> {
            list.add(item);
        });
        return new ResponseResult<>(200,"查询成功",list);
    }
    /**
     * @description: 商品索引分页查询
     * @param: [pageNum, pageSize]
     * @return: com.jk.smartelderlycare.pojo.ResponseResult<com.jk.smartelderlycare.pojo.PagedResponse<com.jk.smartelderlycare.entity.Product>>
     * @author hhk
     * @date: 2024/11/12 19:08
     */
    @ApiOperation(value = "商品索引分页查询",httpMethod = "GET",notes = "商品索引分页查询")
    @GetMapping(value = "/testPagQuery")
    public ResponseResult<PagedResponse<Product>> testPagQuery( Integer pageNum, Integer pageSize){
        //设置排序(排序方式，正序还是倒序，排序的 id)
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        //设置分页(页码，每页显示的条数)
        //当前页码0开始
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize, sort);
        Page<Product> productPage = productDao.findAll(pageRequest);
        PagedResponse<Product> pagedResponse = PaginationUtil.getPagedResponse(productPage.getContent(), pageNum, pageSize, productPage.getTotalElements());
        return new ResponseResult<>(200,"查询成功",pagedResponse);
    }
    
    /** 
     * @description: 商品高亮显示
     * @param: [keyword]
     * @return: com.jk.smartelderlycare.pojo.ResponseResult<java.util.List<com.jk.smartelderlycare.entity.Product>>
     * @author hhk
     * @date: 2024/11/12 19:26
     */ 
    @ApiOperation(value = "商品高亮显示",httpMethod = "GET",notes = "商品高亮显示")
    @GetMapping(value = "testHighlightQuery")
    public  ResponseResult<List<Product>> testHighlightQuery(String keyword){
        List<Product> list = new ArrayList<>();
        //构建查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.matchQuery("title",keyword));

        //设置高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("title");

        //构建查询
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQuery)
                .withHighlightBuilder(highlightBuilder)
                .build();
        //执行查询
        SearchHits<Product> searchHits = elasticsearchRestTemplate.search(nativeSearchQuery, Product.class);
        //获取查询结果
        searchHits.forEach(searchHit ->{
            Product product = searchHit.getContent();
            //重新赋值高亮字段
            product.setTitle(searchHit.getHighlightField("title").get(0));
            list.add(product);
        });
        return new ResponseResult<>(200,"查询成功",list);
    }

    @ApiOperation(value = "商品列表分页查询高亮显示",httpMethod = "GET",notes = "商品列表分页查询高亮显示")
    @GetMapping(value = "testHighlightByPage")
    public ResponseResult<PagedResponse<Product>> testHighlightByPage(String keyword,Integer pageNum,Integer pageSize){
        List<Product> list = new ArrayList<>();
        //设置排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        //设置分页
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize, sort);
        //设置查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.should(QueryBuilders.matchQuery("title",keyword));
        //按照类型
        boolQuery.should(QueryBuilders.matchQuery("category",keyword));
        //设置高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("title");
        highlightBuilder.field("category");
        //构建查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQuery)
                .withHighlightBuilder(highlightBuilder)
                .withPageable(pageRequest)
                .build();
        //执行查询
        SearchHits<Product> searchHits =  elasticsearchRestTemplate.search(searchQuery,Product.class);
        searchHits.forEach(searchHit ->{
            Product product = searchHit.getContent();
            //重新赋值高亮字段
            product.setTitle(searchHit.getHighlightField("title").get(0));
            product.setCategory(searchHit.getHighlightField("category").get(0));
            list.add(product);
        });
        return new ResponseResult<>(200,"查询成功",PaginationUtil.getPagedResponse(list,pageNum,pageSize,searchHits.getTotalHits()));
    }

















}
